import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { EntityManager, getManager } from "typeorm";
import { AccessDto } from "../dto/access.dto";
import { Access } from "../entities/access.entity";

@Injectable()
export class AccessService {
    async create(accessDto: AccessDto) {
        const u = await Access.findOne({ where: { accessName: accessDto.accessName } });

        if (u) {
            throw new HttpException({
                message: 'Input data validation failed',
                error: 'roleName must be unique',
            },
                HttpStatus.BAD_REQUEST);
        }
        const access = new Access();
        access.accessName = accessDto.accessName;
        if (accessDto.remark) {
            access.remark = accessDto.remark;
        }
        return getManager().transaction(async (entityManager: EntityManager) => {
            return await entityManager.save(access);
        })

    }

    async findAll() {
        return await Access.find();
    }

    async update(accessDto: AccessDto) {
        if (accessDto.id) {
            throw new HttpException({
                message: 'Input data validation failed',
                error: 'id must be exist',
            },
                HttpStatus.BAD_REQUEST);
        }
        const access = await Access.findOne({ where: { id: accessDto.id } });

        access.accessName = accessDto.accessName;
        if (accessDto.remark) {
            access.remark = accessDto.remark;
        }
        return getManager().transaction(async (entityManager: EntityManager) => {
            return await entityManager.save(access);
        })

    }

    async delete(id: number) {
        await Access.delete(id);
        const access = await Access.findOne({ where: { id: id } });
        if (access) {
            return false;
        }
        return true;
    }
}